package Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import DAL.Entites.Recommendation;
import DAL.JDBC.DBConn;
import DAL.JDBC.RecommendationJDBC;

public class AddRecommendation extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public AddRecommendation() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject result = new JSONObject();
		RecommendationJDBC recommendationJDBC= new RecommendationJDBC(DBConn.getConnection());
		
		int gameId = Integer.parseInt(request.getParameter("gameId"));
		String recommendationText = request.getParameter("recommendation");
		int userID = Integer.parseInt(request.getParameter("userId"));
		//int userID = Integer.parseInt(request.getSession().getAttribute("userId"));
		
		Recommendation recommendation = recommendationJDBC.getRecommendationForUserAndGame(userID, gameId);
		try {
			if(recommendation != null)
			{
				result.put("result", false);
				result.put("message", "User Already Recommend This Game");
			}
			else if(recommendationText == "")
			{
				result.put("result", false);
				result.put("message", "Must Enter Recommendation");
			}
			else
			{
				recommendationJDBC.insert(gameId, userID, recommendationText);
				result.put("result", true);
			}
		} 
		catch (JSONException e) {
			e.printStackTrace();
		}
		
		PrintWriter pw = response.getWriter();
		pw.write(result.toString());
	}

}
